package com.lu.controller;

import com.alibaba.fastjson.JSONObject;
import com.lu.bean.ResBean;
import com.lu.bean.UserBean;
import com.lu.dao.po.WgRiddle;
import com.lu.dynamicload.JavaclassExecuter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;

/**
 * @author issuser
 * @ClassName IndexController
 * @Description
 * @date 2021/06/16 17:38
 */
@Slf4j
@RestController
@Api(tags = "测试类")
public class IndexController {

    @RequestMapping(value = "/",produces = "text/xml;", method = RequestMethod.GET)
    @ApiOperation(hidden = true, value = "")
    public String defaultGage(HttpServletResponse rsp) throws  Exception{
        rsp.addHeader("Content-Language","en-US");
        rsp.addHeader("Transfer-Encoding","chunked");
        ResBean res = new ResBean();
        res.setResCode("1000");
        res.setResMsg("成功啦,good!");
        res.setData(new WgRiddle());
        String xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?><resp>成功啦</resp>";
        return xml;
    }


    @RequestMapping(value = "/index", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(hidden = true, value = "")
    public String index(@RequestBody UserBean user, HttpServletRequest request) throws  Exception{
        Map<String, String[]> parameterMap = request.getParameterMap();
        for(String key:parameterMap.keySet()){
            System.out.println("key:"+key+": "+request.getParameter(key));
        }
        System.out.println(JSONObject.toJSONString(user));
        return "Success";
    }

    @RequestMapping(value = "loadClass", method = {RequestMethod.POST})
    @ApiOperation(hidden = true, value = "")
    public String loadClass(MultipartFile file) throws Exception{
        log.info("upload class file to execute");
        if(file == null) {
            log.info("file is null");
            return "param error, file is null";
        }

        InputStream is = file.getInputStream();
        byte[] b = new byte[is.available()];
        is.read(b);
        is.close();
        String execute = JavaclassExecuter.execute(b);
        return execute;
    }
}
